package qianting.news.common.inteceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import qianting.news.common.entity.AuthUser;
import qianting.news.common.entity.State;
import qianting.news.common.utils.AppThreadLocalUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行knife4j的接口
        String path = request.getRequestURI();
        if(path.contains("doc.html")||path.contains("swagger")||path.contains("webjars")||path.contains("api-docs")){
            return true;
        }

        String header_id = request.getHeader("userId");
        if(StringUtils.isEmpty(header_id)) {
            throw new Exception("请先登录");
        }
        Long userId = Long.valueOf(request.getHeader("userId"));
        String username = request.getHeader("username");
        if(userId != null){
            //存入到当前线程中
            AuthUser authUser = new AuthUser(userId, username);
            AppThreadLocalUtil.setUser(authUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtil.clear();
    }
}
